package com.kgcx.order.service;

import com.kgcx.common.eum.OrderEnum;
import com.kgcx.common.utils.AuroraPush;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.order.domain.Order;
import com.kgcx.order.entity.OrderChangeMessage;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class OrderNotifyDriverService {

    private static final String NOTIFY_DRIVER_TYPE_JPUSH = "jpush"; // 极光APP消息推送
    private static final String NOTIFY_DRIVER_TYPE_MQTT = "mqtt"; // MQTT长连接

    private static final Logger LOG = LoggerFactory.getLogger(OrderNotifyDriverService.class);

    @Value("${kgcx.order.notify-user-type:jpush}")
    private String notifyDriverType;
    @Autowired(required = false)
    private MqttClient mqttProducer;


    public void notifyDriver(Order record, String msg) {
        try {
            if (NOTIFY_DRIVER_TYPE_MQTT.equals(notifyDriverType)) {
                notifyDriverByMqtt(record, msg);
            } else if (NOTIFY_DRIVER_TYPE_JPUSH.equals(notifyDriverType)) {
                notifyDriverByJpush(record, msg);
            } else {
                notifyDriverByJpush(record, msg);
            }

            LOG.info(String.format("订单[%s]，给司机[%d]推送订单状态变更信息成功，推送方式为%s。", record.getOrderNo(), record.getDriverId(),
                    notifyDriverType));
        } catch (Exception e) {
            LOG.error(String.format("订单[%s]，给司机[%d]推送订单状态变更信息失败，推送方式为%s。", record.getOrderNo(), record.getDriverId(),
                    notifyDriverType), e);
        }
    }

    private void notifyDriverByMqtt(Order record, String msg)
            throws MqttPersistenceException, MqttException {
        if (mqttProducer == null) {
            LOG.warn(String.format("订单[%s]，MQTT功能未开启，转为jpush推送。请确认kgcx.mqtt.enable配置属性的值是否为true。",
                    record.getOrderNo()));
            notifyDriverByJpush(record, msg);
            return;
        }

        OrderChangeMessage mqMsg = new OrderChangeMessage(record.getOrderNo()
                , OrderEnum.CANCEL_ORDER, OrderChangeMessage.MESSAGE_TYPE_CANCLE, "乘客已取消订单", record.getDriverId());
        String strTopic = OrderEnum.ORDER_STATE_TOPIC + "." + record.getDriverId().toString();

        MqttMessage message = new MqttMessage();
        message.setQos(1);
        message.setRetained(false); // 是否是实时发送的消息
        message.setPayload(JsonUtil.toString(mqMsg).getBytes());

        MqttTopic topic = mqttProducer.getTopic(strTopic);
        topic.publish(message);
    }

    private void notifyDriverByJpush(Order record, String msg) {
        // 发送通知
        AuroraPush.pushTargetForDriver(String.valueOf(record.getDriverId()), msg);

        OrderChangeMessage message = new OrderChangeMessage(record.getOrderNo()
                , OrderEnum.CANCEL_ORDER, OrderChangeMessage.MESSAGE_TYPE_CANCLE, "乘客已取消订单", record.getDriverId());
//        String topic = OrderEnum.ORDER_STATE_TOPIC + "." + record.getDriverId().toString();
        // 发送消息
        AuroraPush.pushTargetMsgForDriver(OrderEnum.ORDER_STATE_TOPIC, JsonUtil.toString(message),
                String.valueOf(record.getDriverId()), AuroraPush.PLATFORM_ANDROID);
    }

}
